import sys
import pygame
import Component
import Setting
from Classicmodel import Classicmodel
from Component import EndBox
from Controller import Director
from Setting import GridInfo


class GameUI:
    def __init__(self, gameset, back_color):
        self.game_set = gameset
        self.screen = None
        #self.grid = []
        self.start_flag = False
        self.back_color = back_color
        # for i in range(16):
        #     list = []
        #     for j in range(30):
        #         list.append(10)
        #     self.grid.append(list)

        self.director = None
        self.mc_controller = None
        self.cb_controller = None
        self.end_box = None
        self.restart_flag = False


    def isVaild(self, i, j):
        flag_i = i >= 0 and i < self.game_set.height
        flag_j = j >= 0 and j < self.game_set.width
        return flag_i and flag_j

    ###############################################################################################################################################

    def clear(self):
        self.screen = None
        self.director = None
        self.mc_controller = None
        self.cb_controller = None
        self.end_box = None
        self.restart_flag = False

    def gameInit(self):
        pygame.init()
        self.gameSet()

    def gameSet(self):
        self.start_flag = False
        self.restart_flag = False
        self.end_box = None
        self.screen = pygame.display.set_mode((1200, 800))
        self.screen.fill(self.back_color)

        pygame.display.set_caption("MineSweeper")

        self.mc_controller = Component.MineCount(100, 50, 50, self.game_set.mine_count,self.back_color)
        self.mc_controller.render(self.screen)

        # self.gt_controller = Component.GameTimer(600,50,50)
        # self.gt_controller.render(self.screen)

        self.cb_controller = Component.ChessBoardHandler(100, 200, self.game_set.width, self.game_set.height, 32)
        self.cb_controller.render(self.screen)

    def callEnd(self, mod):
        self.end_box=Component.EndBox(mod, pygame.Rect(400,250,400,300))
        self.end_box.render(self.screen)


    def gameExe(self):

        running = True
        turn = 0
        set_flag_count = 0
        restart_flag = False

        while running:
            # self.gt_controller.timeCount(self.screen)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:

                    b = event.button

                    if b == 1:
                        x, y = event.pos

                        if self.restart_flag:
                            if self.end_box.beHit(x,y):
                                print("Flag has been set!")
                                restart_flag = True

                        j = (x - 100) // self.cb_controller.grid_size
                        i = (y - 200) // self.cb_controller.grid_size

                        if not self.isVaild(i, j):
                            continue

                        if self.start_flag:
                            print(f"turn {turn}")
                            grid_list = self.director.direct(i, j)
                            self.cb_controller.turn_render(self.screen, grid_list)

                        else:
                            print("start")
                            self.game_set.setFirstClick(i, j)
                            self.director = Director(self.game_set)

                            self.director.start()
                            grid_list = self.director.direct(i, j)
                            self.cb_controller.turn_render(self.screen, grid_list)

                            self.start_flag = True

                        if self.director.isEnd():
                            if self.director.isSuccess():
                                self.callEnd(True)
                                print(f"you are win in turn {turn}")
                            else:
                                self.callEnd(False)
                                print(f"you are lose in turn {turn}")
                            self.restart_flag = True
                        else:
                            turn += 1

                    elif b == 2:

                        x, y = event.pos
                        j = (x - 100) // self.cb_controller.grid_size
                        i = (y - 200) // self.cb_controller.grid_size

                        if not self.isVaild(i, j):
                            continue

                        if self.start_flag:
                            print(f"turn {turn}")
                            grid_list = self.director.preform(i, j)
                            self.cb_controller.turn_render(self.screen, grid_list)

                        else:
                            print("start")
                            self.game_set.setFirstClick(i, j)
                            self.director = Director(self.game_set)

                            self.director.start()
                            grid_list = self.director.direct(i, j)
                            self.cb_controller.turn_render(self.screen, grid_list)

                            self.start_flag = True

                        if self.director.isEnd():
                            if self.director.isSuccess():
                                self.callEnd(True)
                                print(f"you are win in turn {turn}")
                            else:
                                self.callEnd(False)
                                print(f"you are lose in turn {turn}")
                            self.restart_flag = True
                            # running=False
                        else:
                            turn += 1

                    ##################################################################################################################################

                    ##################################################################################################################################
                    elif b == 3:

                        x, y = event.pos
                        j = (x - 100) // self.cb_controller.grid_size
                        i = (y - 200) // self.cb_controller.grid_size

                        if not self.isVaild(i, j):
                            continue

                        if self.start_flag:

                            if self.director.isPlantable(i, j):
                                set_flag_count += 1

                                self.cb_controller.cell_render(self.screen, self.director.plantFlag(i, j))
                                self.mc_controller.changeCount(self.director.calVal(i,j))
                                self.mc_controller.update(self.screen)
                                print(f"turn {turn}  set_flag_count {set_flag_count}")

                        else:
                            print("start")
                            self.game_set.setFirstClick(i, j)
                            self.director = Director(self.game_set)

                            self.director.start()
                            grid_list = self.director.direct(i, j)
                            self.cb_controller.turn_render(self.screen, grid_list)

                            self.start_flag = True
                            turn += 1

                    if restart_flag:
                        self.clear()
                        self.gameSet()

                        turn = 0
                        set_flag_count = 0
                        restart_flag = False

            self.close()

    def classicModelExe(self,f_x = 1,f_y = 1):

        running = True
        turn = 0
        # set_flag_count = 0
        # restart_flag = False

        while running:
            # self.gt_controller.timeCount(self.screen)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                else:

                    if self.start_flag:
                        print(f"turn {turn}")
                        (i, j) = self.director.getNextClick()

                        grid_list = self.director.direct(i, j)

                        self.cb_controller.turn_render(self.screen, grid_list)
                        grid_list = self.director.update(grid_list)
                        self.cb_controller.turn_render(self.screen, grid_list)

                        #self.mc_controller.changeCount(self.director.calVal(i, j)) 1111111111111111111111111111111 需修改成列表形式，下同
                        #self.mc_controller.update(self.screen)

                    else:
                        print("start")
                        self.game_set.setFirstClick(f_x, f_y)
                        self.director = Classicmodel(self.game_set)

                        self.director.start()
                        grid_list = self.director.direct(f_x, f_y)

                        self.director.updateBoard(grid_list)
                        self.cb_controller.turn_render(self.screen, grid_list)
                        grid_list = self.director.update(grid_list)
                        self.cb_controller.turn_render(self.screen, grid_list)

                        #self.mc_controller.changeCount(self.director.calVal(i, j))
                        #self.mc_controller.update(self.screen)

                        self.start_flag = True

                    if self.director.isEnd():
                        if self.director.isSuccess():
                            self.callEnd(True)
                            print(f"you are win in turn {turn}")
                            # todo !!!!!!!!!!!!!!!!!!!!! 仅调试时使用！！！！！！！！！！！！
                            running = False
                        else:
                            self.callEnd(False)
                            print(f"you are lose in turn {turn}")
                            running = False
                        self.restart_flag = True
                    else:
                        turn += 1



            self.close()

    def close(self):
        pygame.display.flip()